<template>
  <div class="edit-upload-test">
    <h2>编辑时上传测试</h2>
    
    <!-- 模拟编辑状态 -->
    <div class="test-section">
      <h3>模拟编辑状态</h3>
      <el-button @click="toggleEditMode" type="primary">
        {{ isEditMode ? '切换到新增模式' : '切换到编辑模式' }}
      </el-button>
      <div class="status-info">
        <strong>当前模式:</strong> {{ isEditMode ? '编辑模式' : '新增模式' }}
      </div>
      <div class="status-info">
        <strong>当前缩略图:</strong> {{ formData.bkThumbnail || '无' }}
      </div>
    </div>

    <!-- 模拟表单 -->
    <div class="form-section">
      <h3>模拟表单</h3>
      <el-form :model="formData" label-width="120px">
        <el-form-item label="出库单号">
          <el-input v-model="formData.outboundOrderNumber" placeholder="出库单号" />
        </el-form-item>
        
        <el-form-item label="缩略图">
          <el-upload
            class="thumbnail-uploader"
            action="#"
            :show-file-list="false"
            :on-success="handleThumbnailSuccess"
            :before-upload="beforeThumbnailUpload"
            :http-request="uploadThumbnail"
          >
            <img 
              v-if="formData.bkThumbnail && isValidImageUrl(formData.bkThumbnail)" 
              :src="getImageUrl(formData.bkThumbnail)" 
              class="thumbnail" 
              @error="handleImageError"
              alt="缩略图"
            />
            <el-icon v-else class="thumbnail-uploader-icon"><Camera /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>

    <!-- 调试信息 -->
    <div class="debug-section">
      <h3>调试信息</h3>
      <el-button @click="showDebugInfo" type="info">显示调试信息</el-button>
      <div v-if="debugInfo" class="debug-content">
        <pre>{{ JSON.stringify(debugInfo, null, 2) }}</pre>
      </div>
    </div>

    <!-- 上传历史 -->
    <div class="history-section">
      <h3>上传历史</h3>
      <div v-for="(item, index) in uploadHistory" :key="index" class="history-item">
        <div><strong>时间:</strong> {{ item.time }}</div>
        <div><strong>模式:</strong> {{ item.mode }}</div>
        <div><strong>文件:</strong> {{ item.fileName }}</div>
        <div><strong>结果:</strong> {{ item.success ? '成功' : '失败' }}</div>
        <div><strong>路径:</strong> {{ item.filePath }}</div>
        <div v-if="item.error"><strong>错误:</strong> {{ item.error }}</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Camera } from '@element-plus/icons-vue'
import { uploadOutboundThumbnail } from '@/api/outboundOrder'

// 配置后端服务器地址（用于图片访问）
const BACKEND_SERVER_URL = 'http://localhost:5265'

const isEditMode = ref(false)
const debugInfo = ref<any>(null)
const uploadHistory = ref<any[]>([])

// 模拟表单数据
const formData = reactive({
  outboundOrderNumber: '',
  bkThumbnail: ''
})

// 切换编辑模式
const toggleEditMode = () => {
  isEditMode.value = !isEditMode.value
  if (isEditMode.value) {
    // 编辑模式：设置一些模拟数据
    formData.outboundOrderNumber = 'CK202412010001'
    formData.bkThumbnail = 'uploads/existing-image'
  } else {
    // 新增模式：清空数据
    formData.outboundOrderNumber = ''
    formData.bkThumbnail = ''
  }
}

// 获取图片URL
const getImageUrl = (url: string): string => {
  if (!url) return ''
  
  // 如果是完整URL，直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  
  // 如果是后端返回的文件路径，使用后端服务器地址
  if (url.includes('uploads/')) {
    return `${BACKEND_SERVER_URL}/uploads/${url.replace(/^uploads\//, '')}`
  }
  
  // 其他情况，尝试作为相对路径处理
  return url
}

// 检查是否为有效的图片URL
const isValidImageUrl = (url: string): boolean => {
  if (!url) return false
  
  // 检查是否为blob URL（本地文件）
  if (url.startsWith('blob:')) return true
  
  // 检查是否为data URL（base64）
  if (url.startsWith('data:image/')) return true
  
  // 检查是否为http/https URL
  if (url.startsWith('http://') || url.startsWith('https://')) return true
  
  // 检查是否为相对路径（以/开头）
  if (url.startsWith('/')) return true
  
  // 检查是否为文件路径（包含常见图片扩展名）
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']
  const lowerUrl = url.toLowerCase()
  return imageExtensions.some(ext => lowerUrl.includes(ext))
}

// 上传前验证
const beforeThumbnailUpload = (file: any) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('缩略图只能是 JPG/PNG/GIF 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('缩略图大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

// 处理上传成功
const handleThumbnailSuccess = (response: any, file: any) => {
  console.log('handleThumbnailSuccess 被调用:', response, file)
  // 不再使用 blob URL，而是使用后端返回的文件路径
  if (response && response.data && response.data.filePath) {
    formData.bkThumbnail = response.data.filePath
  }
}

// 处理上传
const uploadThumbnail = async (options: any) => {
  try {
    const file = options.file
    console.log('开始上传缩略图:', file.name, '模式:', isEditMode.value ? '编辑' : '新增')
    
    const response = await uploadOutboundThumbnail(file)
    console.log('上传响应:', response)
    
    if (response.code === 200 && response.data.success) {
      // 使用后端返回的文件路径，确保是字符串格式
      const filePath = response.data.filePath
      console.log('后端返回的文件路径:', filePath)
      
      // 确保存储的是文件路径而不是 blob URL
      formData.bkThumbnail = filePath
      
      // 调用成功回调，传递响应数据
      options.onSuccess(response)
      ElMessage.success('缩略图上传成功')
      
      // 记录上传历史
      uploadHistory.value.unshift({
        time: new Date().toLocaleString(),
        mode: isEditMode.value ? '编辑' : '新增',
        fileName: file.name,
        success: true,
        filePath: filePath,
        error: null
      })
    } else {
      options.onError(new Error(response.msg || '上传失败'))
      ElMessage.error(response.msg || '缩略图上传失败')
      
      // 记录失败历史
      uploadHistory.value.unshift({
        time: new Date().toLocaleString(),
        mode: isEditMode.value ? '编辑' : '新增',
        fileName: file.name,
        success: false,
        filePath: null,
        error: response.msg || '上传失败'
      })
    }
  } catch (error) {
    console.error('缩略图上传失败:', error)
    options.onError(error)
    ElMessage.error('缩略图上传失败')
    
    // 记录失败历史
    uploadHistory.value.unshift({
      time: new Date().toLocaleString(),
      mode: isEditMode.value ? '编辑' : '新增',
      fileName: options.file.name,
      success: false,
      filePath: null,
      error: error instanceof Error ? error.message : '上传失败'
    })
  }
}

// 处理图片加载错误
const handleImageError = (event: Event) => {
  console.warn('图片加载失败:', event)
}

// 显示调试信息
const showDebugInfo = () => {
  debugInfo.value = {
    isEditMode: isEditMode.value,
    formData: { ...formData },
    backendServerUrl: BACKEND_SERVER_URL,
    windowLocationOrigin: window.location.origin,
    uploadHistory: uploadHistory.value
  }
}
</script>

<style scoped>
.edit-upload-test {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.test-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f5f5f5;
  border-radius: 8px;
}

.status-info {
  margin-top: 10px;
  padding: 8px;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.form-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f0f9ff;
  border: 1px solid #b3d8ff;
  border-radius: 8px;
}

/* 缩略图上传器样式 */
.thumbnail-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.thumbnail-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.thumbnail-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.thumbnail {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

.debug-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #fafafa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.debug-content {
  margin-top: 15px;
  padding: 15px;
  background: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  overflow-x: auto;
}

.debug-content pre {
  margin: 0;
  font-size: 12px;
  line-height: 1.4;
}

.history-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f6ffed;
  border: 1px solid #b7eb8f;
  border-radius: 8px;
}

.history-item {
  margin-bottom: 15px;
  padding: 15px;
  background: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  line-height: 1.6;
}

.history-item div {
  margin-bottom: 5px;
}
</style>



